package com.ruoyi.framework.security.authenticationtoken;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Collection;


/**
 * 手机验证码登录
 */
public class PhoneCaptcheAuthenticationToken extends AbstractAuthenticationToken {

    //记录手机号
    private Object principal;
    //记录验证码(凭证)
    private Object credentials;

    //未认证时候的构造方法
    public PhoneCaptcheAuthenticationToken(Object principal, Object credentials) {
        super((Collection)null);
        this.principal = principal;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        //在这里主要是用于防止有人直接构造一个已认证的token
        //在这里构造时还处于未认证的状态，所以不能为true.当有人直接构造为true的时候抛出后面的错误表达式
        Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    //已认证时候的构造方法
    public PhoneCaptcheAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }

    public static PhoneCaptcheAuthenticationToken authenticated(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        return new PhoneCaptcheAuthenticationToken(principal, credentials, authorities);
    }

    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }
}
